//
//  SQLiteManager.swift
//  UsingFMDB
//
//  Created by 范伟 on 16/3/13.
//  Copyright © 2016年 FanWei. All rights reserved.
//

import Foundation
import FMDB

private let FWDatabaseName = "fwDatabase.db"

class SQLiteManager {

    /// 单例
    static let sharedManager: SQLiteManager = SQLiteManager()
    /// 全局数据库访问队列
    let queue: FMDatabaseQueue
    
    private init() {
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
            .UserDomainMask,
            true)[0]
        path = (path as NSString).stringByAppendingPathComponent(FWDatabaseName)
        print("数据库路径：\(path)")
        // 初始化队列 (SQLite做法：sqlit3_openDB -> &db 返回全局操作句柄)
        // 参数：数据库文件的完整路径
        // - 如果数据库不存在，会新建`空白`数据库，并且实例化队列
        // - 如果数据库存在，会打开数据库，并且实例化队列
        queue = FMDatabaseQueue(path: path)
        createTable()
    }
    
    private func createTable() {
        //准备sql
        guard let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil) else {
            return
        }
        let sql = try! String(contentsOfFile: path)
        //执行sql
        queue.inDatabase { (db) -> Void in
            if db.executeStatements(sql) {
                print("Create table success!")
            } else {
                print("Create table failed!")
            }
        }
    }
}